/*
 * @Author: Haochen
 * @Date: 2021-11-22 10:22:14
 * @LastEditTime: 2021-11-26 17:28:12
 * @FilePath: \front\src\js\exam_paper.js
 */

import $ from './jquery-3.6.0.min.js';
import '../scss/common.scss';
import '../scss/exam-paper.scss';
import { backToIndex, getPromise } from './common';

backToIndex();

const testType = window.location.search
  .substring(1)
  .split('?')[0]
  .split('=')
  .pop();

var testId = window.location.search.substring(1).split('=').pop();

$(function () {
  var strDataQuery = '/testsRouter/:' + testId;

  async function getDataAndRender() {
    const { code, data, message } = await getPromise(strDataQuery, 'get', {});
    // console.log('dataBack: ', data);
    render(data);
  }

  getDataAndRender();

  let minutes = 29;
  let seconds = 59;

  $('#minutes').text(minutes);
  $('#seconds').text(seconds);

  window.setInterval(function () {
    if (seconds == 0) {
      seconds = 59;
    }
    seconds--;
    if (seconds < 10) {
      $('#seconds').text('0' + seconds);
    } else {
      $('#seconds').text(seconds);
    }
  }, 1000);

  window.setInterval(function () {
    minutes--;
    $('#minutes').text(minutes);
  }, 59000);

  function render(data) {
    const examType = data[0].typeId.type;
    const examTitle = data[0].title;

    const exercises = data[0].exercisesId;
    const MAX_NUM_Q = exercises.length;
    const answers = new Array(MAX_NUM_Q).fill(-1);

    $('.nav-main').append(`
      <h3>${examTitle}</h3>
    `);

    $('.exam-type').text(`${examType}`);

    $('.total').text(MAX_NUM_Q);
    $('.unanswered').text(MAX_NUM_Q);

    for (let i = 0; i < MAX_NUM_Q; i++) {
      $('.sb-box-3').append(`
          <div class="rect-box" boxnum = "${i}">${i + 1}</div>
      `);

      $('.content-question').append(`
    
         <div class="question-context" order="${i}">

            <h5 class="question-text">
                ${exercises[i].topics}
            </h5>
                    <ul class="answers">
                        <li answerIndex="0">
                            <div class="circle-box">A</div>
                            <span class="answer-text">${exercises[i].options[0]}</span>
                        </li>
                        <li answerIndex="1">
                            <div class="circle-box">B</div>
                            <span class="answer-text">${exercises[i].options[1]}</span>
                        </li>
                        <li answerIndex="2">
                            <div class="circle-box">C</div>
                            <span class="answer-text">${exercises[i].options[2]}</span>
                        </li>
                        <li answerIndex="3">
                            <div class="circle-box">D</div>
                            <span class="answer-text">${exercises[i].options[3]}</span>
                        </li>
                    </ul>
                  
            </div>
        
    
      `);

      if (i > 0) {
        $(`.question-context:eq(${i})`).hide();
      }
    }

    let cur_i = $(`.question-context:visible`).attr('order'); // * 当前所在题目的下标

    // * 选项功能
    $('.answers').on('click', 'li', function () {
      // * 实现单选
      $(this).siblings().children('.circle-box').removeClass('circle-selected');
      $(this).children('.circle-box').addClass('circle-selected');

      answers[cur_i] = parseInt($(this).attr('answerIndex'));
      // console.log(answers);
    });

    // * 跳到指定题目
    $('.sb-box-3').on('click', '.rect-box', function () {
      cur_i = parseInt($(`.question-context:visible`).attr('order'));

      if (answers[cur_i] !== -1) {
        $(`.sb-box-3 .rect-box:eq(${cur_i})`).addClass('answered');
      }

      cur_i = parseInt($(this).attr('boxnum')); // 点击右侧边栏的小盒子所对应的题目下标
      // console.log('current page index:', cur_i);

      $('.order').text(`${cur_i + 1}`);
      $('.unanswered').text('' + countQuestionUnanswered(answers, MAX_NUM_Q));
      $(`.question-context`).hide();
      $(`.question-context:eq(${cur_i})`).fadeIn(500);
    });

    // * 跳到下一题
    // let clickCount = 0;

    $('#btn-next-question').click(function () {
      // console.log('click', ++clickCount, 'time(s)');
      if (cur_i < MAX_NUM_Q - 1) {
        cur_i = parseInt($(`.question-context:visible`).attr('order'));

        $(`.question-context:eq(${cur_i})`).hide();
        $(`.question-context:eq(${cur_i + 1})`).fadeIn(500);

        $('.unanswered').text(countQuestionUnanswered(answers, MAX_NUM_Q));

        if (answers[cur_i] !== -1) {
          $(`.sb-box-3 .rect-box:eq(${cur_i})`).addClass('answered');
        }

        cur_i = parseInt($(`.question-context:visible`).attr('order'));

        $('.order').text(cur_i + 1);

        // console.log('current page index:', cur_i);

        return true;
      } else {
        $('.unanswered').text(countQuestionUnanswered(answers, MAX_NUM_Q));

        if (answers[cur_i] !== -1) {
          $(`.sb-box-3 .rect-box:eq(${cur_i})`).addClass('answered');
        }

        alert('已经是最后一题');

        return false;
      }
    });

    // * 提交考试
    $('#btn-submit-exam').click(function () {
      let toSubmit = null;
      if (countQuestionUnanswered(answers, MAX_NUM_Q) > 0) {
        toSubmit = confirm(
          `确定交卷吗, 你还有${countQuestionUnanswered(
            answers,
            MAX_NUM_Q
          )}题未答`
        );
      } else {
        toSubmit = confirm(`确定交卷吗？要不再检查检查`);
      }

      // * 确认提交考试
      if (toSubmit) {
        const minsUsed = 29 - minutes;
        const secsUsed = 59 - seconds;

        const users = JSON.parse(localStorage.getItem('users'));
        const userId = users.find((user) => user.status === 'online')._id;

        const results = {
          score: 0,
          studentId: userId,
          testId: testId,
          options: answers,
          timeUsed: minsUsed + '分: ' + secsUsed + '秒',
        };

        async function postData(input) {
          const { code, data, message } = await getPromise(
            '/exercisesRouter/score',
            'get',
            input
          );

          results.score = data.totalScore;

          const {
            code: code1,
            data: data1,
            message: message1,
          } = await getPromise('/errorsRouter/', 'post', {
            errors: JSON.stringify(data.errors),
          });

          console.log(message1);

          const {
            code: code2,
            data: data2,
            message: message2,
          } = await getPromise('/testedsRouter/', 'post', results);

          console.log(message2);
        }

        postData(results);

        let timer = setTimeout(function () {
          location.href = `./exam_score.html?type=${testType}?id=${testId}`;
        }, 2000);
      } else {
        return false;
      }
    });
  }
});

$('.btn-back-to-exam').click(function () {
  location.href = `./exam_info.html?type=${testType}?id=${testId}`;
});

function countQuestionUnanswered(answers, initialCount) {
  let answered = 0;
  for (const answer of answers) {
    if (answer !== -1) answered++;
  }
  return '' + (initialCount - answered);
}
